package core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import utility.file.TextFile;
import utility.lines.Lines;
import words.parser.QuestionParser;
import algorithm.measures.ConfusionMatrix;
import algorithm.winnow.TestWinnowCommittee;

public class Tester {
	
	private Map<String,TestWinnowCommittee> _categoryToCommittee;
	private int _totalTestQuestions;
	private ConfusionMatrix _matrix;

	public Tester(){
		_categoryToCommittee = new HashMap<String, TestWinnowCommittee>();
		_matrix = new ConfusionMatrix();
		_totalTestQuestions = 0;
	}

	public void put(String category, TestWinnowCommittee testCommittee) {
		_categoryToCommittee.put(category, testCommittee);
	}

	public void test(String question) {
		QuestionParser parser = new QuestionParser(question);
		String cleanQuestion = parser.cleanQuestion();
		String category = parser.category();
		List<String> positivePredictors = new ArrayList<String>();
		
		for (String each : _categoryToCommittee.keySet()) {
			TestWinnowCommittee committee = _categoryToCommittee.get(each);
			boolean positiveTest = category.equals(committee.category());
			boolean positivePrediction = committee.belongsToCategory(cleanQuestion,positiveTest);
			if(positivePrediction) positivePredictors.add(each);
		}
				
		_totalTestQuestions++;
		
		if(positivePredictors.size()!=1) return;
		
		String predictedCategory = positivePredictors.get(0);
		_matrix.incrementValueOn(category, predictedCategory);
	}

	public void writeResultsOn(TextFile file) {
		for (String each : _categoryToCommittee.keySet()) {
			TestWinnowCommittee committee = _categoryToCommittee.get(each);
			committee.writeResultsForOn(_totalTestQuestions,file);
		}
		file.putLine(";;;;;;");
		file.putLine(";;;;;;");
		_matrix.writeMatrixForOn(_totalTestQuestions, file);
	}

	public String result() {
		Lines result = new Lines();
		
		for (String each : _categoryToCommittee.keySet()) {
			TestWinnowCommittee committee = _categoryToCommittee.get(each);
			result.putLine("");
			result.putLine(each);
			for (String eachWord : committee.bestExperts(5)) {
				result.putLine(eachWord);
			}
		}
		return result.asText();
	}

	public void makeTfIdf() {
		Map<String,Integer> allTermsToOcurrence = new HashMap<String,Integer>();
		for (String each : _categoryToCommittee.keySet()) {
			TestWinnowCommittee committee = _categoryToCommittee.get(each);
			committee.putAllTermsAndUpdate(allTermsToOcurrence);
//			committee.setThresholdCoefficient(0.0000000001);
		}
		
		for (String each : allTermsToOcurrence.keySet()) {
			int totalOccurrences = allTermsToOcurrence.get(each);
			for (String category : _categoryToCommittee.keySet()) {
				TestWinnowCommittee committee = _categoryToCommittee.get(category);
				committee.makeTFIDFOnUsing(each,totalOccurrences,_categoryToCommittee.size());
			}
		}
	}

}
